//
//  ThingsSuggestTableViewController.m
//  糗事百科
//
//  Created by lanou on 16/5/28.
//  Copyright © 2016年 刘恒春. All rights reserved.
//

//图文页面

#import "ThingsSuggestTableViewController.h"
#import "RequestManager.h"
#import "ThingsListModel.h"
#import "ThingstextTableViewCell.h"
#import "ThingsimageTableViewCell.h"
#import "timeTool.h"
#import "ThingsvideoTableViewCell.h"
#import "VideoPlayer.h"
#import "ThingsInfoViewController.h"
@interface ThingsSuggestTableViewController ()<UIScrollViewDelegate>{
    NSIndexPath *_indexPath;
    VideoPlayer *_player;
    CGRect _currentPlayCellRect;
}
@property (nonatomic,strong) NSMutableArray *datasource;
@property (nonatomic,assign)CGFloat strh;
@property (nonatomic,assign) NSInteger page;
@end

@implementation ThingsSuggestTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //数组初始化
    _datasource = [NSMutableArray array];
    //网络请求
    _page = 1;
    [self netrequset];
    //注册三种类型cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ThingstextTableViewCell" bundle:nil] forCellReuseIdentifier:@"textcell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ThingsimageTableViewCell" bundle:nil] forCellReuseIdentifier:@"imacell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ThingsvideoTableViewCell" bundle:nil] forCellReuseIdentifier:@"videocell"];
    
    // 下拉刷新数据
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^
    {
        // 下拉刷新数据 需要重新网络请求
        _page= 1;
        [_datasource removeAllObjects];
        [self netrequset];
    }];
    
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^
    {
        _page = _page+1;
        //再次请求数据
        [self netrequset];
    }];

}
#pragma mark - tableview行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _datasource.count;
}
#pragma mark - 返回tableviewcell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ThingsListModel  *model = _datasource[indexPath.row];
    NSString *type = model.format;
    NSString *idstring = [NSString stringWithFormat:@"%@",model.user.uid];
    NSString *substring = [idstring substringToIndex:idstring.length/2];
    NSString *urlstring = [NSString stringWithFormat:@"%@/%@/medium/%@",substring,idstring,model.user.icon];
    NSNumber *like =[NSNumber numberWithInt:[model.votes.up intValue] + [model.votes.down intValue]];
    
    if ([type isEqualToString:@"word"])
    {
        ThingstextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textcell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        if ([model.type isEqualToString:@"hot"])
        {
            cell.texttype.image =[UIImage imageNamed:@"hot"];
        }else if([model.type isEqualToString:@"fresh"])
        {
            cell.texttype.image = [UIImage imageNamed:@"fresh"];
        }
        if (model.user.login ==NULL)
        {
            cell.texticon.image =[UIImage imageNamed:@"jijun"];
            cell.textuname.text =@"匿名用户";
        }
        [cell.texticon sd_setImageWithURL:[NSURL URLWithString:[kiconurl stringByAppendingString:urlstring]]];
        cell.textuname.text = model.user.login;
        cell.textcontent.text = model.content;
        cell.likecount.text = [NSString stringWithFormat:@"%@",like];
        cell.commmentcout.text =[NSString stringWithFormat:@"%@",model.comments_count];
        cell.texttime.text = [[timeTool alloc] publishtime:[NSString stringWithFormat:@"%@",model.published_at]];
        
        return cell;
    }
    else if ([type isEqualToString:@"image"])
    {
        ThingsimageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imacell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        
        NSString *imastr = [model.image substringWithRange:NSMakeRange(3,9)];
        NSString *subimastr = [model.image substringWithRange:NSMakeRange(3,5)];
        NSString *imaurlstr = [NSString stringWithFormat:@"%@/%@/medium/%@",subimastr,imastr,model.image];
        
        if ([model.type isEqualToString:@"hot"])
        {
            cell.imaright.image =[UIImage imageNamed:@"hot"];
        }else if([model.type isEqualToString:@"fresh"])
         {
             cell.imaright.image = [UIImage imageNamed:@"fresh"];
         }
         
         if (model.user.login ==NULL)
         {
             cell.imaicon.image = [UIImage imageNamed:@"jijun"];
             cell.imauname.text = @"匿名用户";
     
         }
         [cell.imaicon sd_setImageWithURL:[NSURL URLWithString:[kiconurl stringByAppendingString:urlstring]]];
         cell.imauname.text = model.user.login;
         cell.imatime.text = [[timeTool alloc] publishtime:[NSString stringWithFormat:@"%@",model.published_at]];
         cell.imacontent.text = model.content;
         [cell.imapic sd_setImageWithURL:[NSURL URLWithString:[kimaurl stringByAppendingString:imaurlstr]]];
         cell.imapic.frame =CGRectMake(10, 80+_strh, [model.image_size.s[0] floatValue], [model.image_size.s[1] floatValue]);
         cell.likecout.text = [NSString stringWithFormat:@"%@",like];
         cell.commmentcount.text =[NSString stringWithFormat:@"%@",model.comments_count];
         return cell;
    }
    else
    {
        ThingsvideoTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"videocell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        cell.videomodel = model;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showVideoPlayer:)];
        [cell.videoImageView addGestureRecognizer:tap];
        cell.videoImageView.tag = indexPath.row + 100;
        [cell.videoicon sd_setImageWithURL:[NSURL URLWithString:[kiconurl stringByAppendingString:urlstring]]];
        cell.videoTitle.text = model.user.login;
        cell.videotime.text = [[timeTool alloc] publishtime:[NSString stringWithFormat:@"%@",model.published_at]];
        cell.videocontent.text = model.content;
        cell.videolagu.text = [NSString stringWithFormat:@"%@",like];
        cell.videocomment.text =[NSString stringWithFormat:@"%@",model.comments_count];
        cell.videoshare.text = [NSString stringWithFormat:@"%@",model.share_count];
        cell.videoloop.text = [NSString stringWithFormat:@"%@",model.loop];
        return cell;
    
    }
}
#pragma mark - 动态返回cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ThingsListModel  *model = _datasource[indexPath.row];
    NSString *type = model.format;
    if ([type isEqualToString:@"word"])
    {
        CGFloat  f=  [self heightForString:model.content size:14];
        return f+160;
    }
    else if ([type isEqualToString:@"image"])
    {
        _strh =  [self heightForString:model.content size:14];
        NSArray *arr=model.image_size.s;
        NSNumber *ima =arr[1];
        CGFloat imah =[ima floatValue];
        return _strh+160+imah;
    }
    else
    {
        return 370;
    }
}
- (CGFloat)heightForString:(NSString *)aString size:(NSInteger)size
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
    CGRect rect = [aString boundingRectWithSize:CGSizeMake(300, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}
#pragma mark - celld点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ThingsListModel *model =_datasource[indexPath.row];
    NSString *idstring = [NSString stringWithFormat:@"%@",model.user.uid];
    NSString *substring = [idstring substringToIndex:idstring.length/2];
    NSString *urlstring = [NSString stringWithFormat:@"%@/%@/medium/%@",substring,idstring,model.user.icon];
    
    NSString *imastr = [model.image substringWithRange:NSMakeRange(3,9)];
    NSString *subimastr = [model.image substringWithRange:NSMakeRange(3,5)];
    NSString *imaurlstr = [NSString stringWithFormat:@"%@/%@/medium/%@",subimastr,imastr,model.image];
    
    ThingsInfoViewController *infoVc = [[ThingsInfoViewController alloc ] init];
    infoVc.infoid = model.ID;
    infoVc.infoicon = [kiconurl stringByAppendingString:urlstring];
    infoVc.infouname = model.user.login;
    infoVc.infocontent = model.content;
    infoVc.infolikecount = [NSString stringWithFormat:@"%@",[NSNumber numberWithInt:[model.votes.up intValue] + [model.votes.down intValue]]];
    infoVc.infocommmentcout=[NSString stringWithFormat:@"%@",model.comments_count];
    infoVc.infoima =[kimaurl stringByAppendingString:imaurlstr];
    infoVc.type = model.format;
    infoVc.imah = [model.image_size.s[1] floatValue];
    infoVc.imaw = [model.image_size.s[0] floatValue];
    infoVc.mp4_url =model.high_url;
    [self.navigationController pushViewController:infoVc animated:YES];
}
#pragma mark - 网络请求
-(void)netrequset
{
    [RequestManager initWithUrlString:[NSString stringWithFormat:@"%@?page=%ld",_SuggestUrl,(long)_page]requestType:@"GET" parDic:nil finishBlock:^(NSData *data)
     {
         
         NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
         NSArray *listArray = dataDic[@"items"];
         
         for (NSDictionary *dic in listArray)
         {
             ThingsListModel *model =[[ThingsListModel alloc]init];
             [model setValuesForKeysWithDictionary:dic];
             [_datasource  addObject:model];
         }
         dispatch_async(dispatch_get_main_queue(), ^
        {
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        });
         
         NSLog(@"图文请求成功");
         
     } errorBlock:^(NSError *error)
     {
         NSLog(@"图文请求失败");
     }];
}
#pragma mark - 视频播放相关
-(VideoPlayer *)player
{
    if (!_player)
    {
        _player = [[VideoPlayer alloc] init];
        _player.frame = CGRectMake(1, 1, 1, 1);
    }
    return _player;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_player destroyPlayer];
    _player = nil;
}
- (void)showVideoPlayer:(UITapGestureRecognizer *)tapGesture
{
    [_player destroyPlayer];
    _player = nil;
    
    UIView *view = tapGesture.view;
    ThingsListModel *item = self.datasource[view.tag - 100];
    
    _indexPath = [NSIndexPath indexPathForRow:view.tag - 100 inSection:0];
    ThingsvideoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:_indexPath];
    
    _player = [[VideoPlayer alloc] init];
    _player.videoUrl = item.high_url;
    [_player playerBindTableView:self.tableView currentIndexPath:_indexPath];
    _player.frame = view.frame;
    
    [cell.contentView addSubview:_player];
    
    _player.completedPlayingBlock = ^(VideoPlayer *player)
    {
        [player destroyPlayer];
        _player = nil;
    };
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([scrollView isEqual:self.tableView]) {
        
        [_player playerScrollIsSupportSmallWindowPlay:YES];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}




@end

